<template>
  <div class="content">
    <el-dialog
      title="优惠码列表"
      :visible.sync="visible"
      :close-on-click-modal="false"
      width="80%"
      @close="visible = false"
    >
      <div class="mt-[-25px]">
        <!-- 头部基本信息 -->
        <div class="top-content" v-if="frow">
          <div class="top-content-tit">
            <div>{{ frow.name }}</div>
            <div>
              <el-tag class="item" effect="dark">
                {{ stateObj[showDelete(frow)] }}
              </el-tag>
            </div>
          </div>
          <div class="pad">
            <template v-if="frow.preferenceType">单商品免单</template>
            <template v-else>
              <template v-if="frow.purchaseAbove">
                订单满{{ frow.purchaseAbove | $cent2yuan }}元
              </template>
              <template v-else>无门槛</template>
              减免 {{ frow.preferenceNum | $cent2yuan }}元
            </template>
          </div>
          <div v-if="frow.validTimeType == 0">
            可用时间：{{ frow.useStartTime }} 至 {{ frow.useEndTime }}
          </div>
          <div v-else>
            可用时间：
            <span>{{ frow.useTimePeriod }}</span>
            天内可用
          </div>
        </div>
        <!-- table头部搜索 -->
        <el-form ref="listFilterRef" :model="list.filter" inline class="list-filter">
          <el-form-item prop="couponCode">
            <el-input
              v-model="list.filter.couponCode"
              placeholder="兑换码"
            ></el-input>
          </el-form-item>
          <el-form-item prop="phone">
            <el-input
              v-model="list.filter.phone"
              placeholder="领取人"
            ></el-input>
          </el-form-item>
          <el-form-item prop="frontStatus">
            <KiSelect
              v-model="list.filter.frontStatus"
              placeholder="请选择活动状态"
              :options="frontStatusList"
            />
          </el-form-item>
          <el-form-item>
            <el-button @click="reset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="edit-tab">
        <div class="table-operation">
          <div class="pb-10px" v-if="frow">
            <el-button
              type="primary"
              :disabled="!(showDelete(frow) == 0 || showDelete(frow) == 1)"
              @click="add"
            >
              增加总量
            </el-button>
            <ExportExcel
              :authBtn="false"
              url="/sot-admin-api/product/couponActivity/couponExport"
              :param="list.filter"
              name="导出列表"
            />
          </div>
          <el-pagination
            v-bind="elPaginationProps"
            :total="list.total"
            :currentPage.sync="list.filter.pageNo"
            :pageSize.sync="list.filter.pageSize"
            :page-sizes="[5, 10, 20, 50, 100]"
          />
        </div>
        <el-table
          stripe
          v-loading="list.loading"
          :data="list.data"
          border
          fit
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            :selectable="row => row.status === 0 || row.status === 1"
          />
          <el-table-column label="优惠码ID" prop="id" />
          <el-table-column label="优惠码密钥" prop="couponCode" />
          <el-table-column label="创建时间" prop="createTime" />
          <el-table-column label="券状态" prop="status">
            <template slot-scope="{ row }">
              {{ row.statusStr }}
            </template>
          </el-table-column>
          <el-table-column label="领取人" prop="phone" />
          <el-table-column label="领取时间" prop="distributeTime" />
          <el-table-column label="使用时间" prop="usedTime" />
          <el-table-column align="center" label="操作" width="320">
            <template slot-scope="{ row }">
              <el-button
                v-if="row.status == 0 || row.status == 1"
                type="text"
                @click="forbidden(row)"
              >
                禁用
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer">
        <el-button
          type="primary"
          :loading="loading"
          v-if="tabDataR.length"
          @click="forbidden()"
        >
          禁 用
        </el-button>
        <el-button @click="visible = false">关 闭</el-button>
      </span>
    </el-dialog>
    <!-- 增加总量 -->

    <KiFormDialog
      :show.sync="showAdd"
      title="添加总量"
      v-model="addform"
      :submit="addFormSubmit"
      ref="formRef"
      :loading="addLoading"
    >
      <template #el-form>
        <el-form-item label="发放数量" label-width="90px">
          <span>{{ labelNum }}</span>
        </el-form-item>
        <el-form-item
          label="添加库存"
          :verify="{ type: 'int', lte: 5000 }"
          label-width="90px"
          prop="num"
        >
          <el-input
            v-model="addform.num"
            placeholder="单次添加请勿超过5000个"
          ></el-input>
        </el-form-item>
      </template>
    </KiFormDialog>
  </div>
</template>
<script>
import pageMixin from '@/utils/pageMixin'
import useAdmateAdapter from '@/utils/useAdmateAdapter'
let self = null
export default {
  mixins: [pageMixin],
  setup: () =>
    useAdmateAdapter({
      urlPrefix: 'sot-admin-api/product/couponActivity',
      axiosConfig: {
        getList: {
          url: 'queryCouponPage'
        }
      },
      getListProxy (getList) {
        if (self && self.frow) {
          self.list.filter.couponActivityId = self.frow.id
          getList()
        }
      },
      list: {
        filter: {
          couponCode: '',
          phone: '',
          frontStatus: '',
          pageSize: 5
        }
      }
    }),
  data () {
    return {
      frow: null,
      frontStatusList: [
        { dataName: '未领取', dataValue: 0 },
        { dataName: '已领取', dataValue: 1 },
        { dataName: '已使用', dataValue: 2 },
        { dataName: '已失效', dataValue: 3 },
        { dataName: '已过期', dataValue: 4 }
      ],

      visible: false,
      showAdd: false,
      addform: { num: null },
      addLoading: false,
      stateObj: {
        0: '未开始',
        1: '进行中',
        2: '已结束',
        3: '已失效'
      },
      tabDataR: []
    }
  },
  computed: {
    labelNum () {
      return `${this.list.total}个`
    }
  },
  created () {
    self = this
  },
  methods: {
    show (row) {
      this.visible = true
      this.$nextTick(() => {
        this.frow = row
        this.reset()
        this.list.filter.pageNo = 1
        this.getList()
      })
    },
    showDelete (row) {
      let da = row.status
      let s1 = new Date().getTime() //当前时间
      let s2 = new Date(row.useEndTime).getTime() //结束时间
      let s3 = new Date(row.useStartTime).getTime() // 开始时间

      if (row.status == 2) {
        return 3
      }

      // 领取后n天可用类型，默认活动永久
      if (row.validTimeType == 1) {
        return 1
      }

      if (da == 3) {
        //失效
        return 3
      }
      if (s2 - s1 < 0) {
        //结束
        return 2
      }
      if (s3 < s1 && s1 < s2) {
        //进行中
        return 1
      }
      if (s1 < s3) {
        //未开始
        return 0
      }
    },

    // 增加总量
    add () {
      this.showAdd = true
    },
    handleSelectionChange (val) {
      this.tabDataR = val
    },
    addFormSubmit () {
      let data = Object.assign({ id: this.frow.id }, this.addform)
      this.addLoading = true
      this.$POST('/sot-admin-api/product/couponActivity/addCouponNum', data)
        .then(res => {
          if (res.errorCode == '00000') {
            this.$swal.success('添加成功')
            this.showAdd = false
            this.list.filter.pageNo = 1
            this.getList()
          }
          this.addLoading = false
        })
        .catch(err => {
          this.$swal.warning(err.message)
          this.addLoading = false
        })
    },
    /**禁用:只有处于未领取、已领取状态时，支持禁用操作
     * 	d) 批量禁用按钮
        列表左侧有复选框，列表只有未领取状态可支持选择，
        顶端复选框勾选时表示该页处于未领取状态的信息全选。
     */
    forbidden (row) {
      this.$confirm(
        '禁用后，未使用的优惠码无法领取，已领取的优惠码将无法使用，请提前告知用户。请确定是否禁用?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        this.loading = true
        let da = []
        let data = {}
        if (row) {
          da = [row.id]
        } else if (this.tabDataR.length > 0) {
          da = this.tabDataR.map(item => item.id)
        }
        data = {
          couponActivityId: this.frow.id,
          ids: da
        }
        this.$POST(
          '/sot-admin-api/product/couponActivity/disableCouponBatch',
          data
        )
          .then(res => {
            if (res.errorCode == '00000') {
              this.$swal.success('禁用成功')
              this.tabDataR = []
              this.getList()
            }
          })
          .finally(_ => {
            this.loading = false
          })
      })
    }
  },
  filters: {
    getStatus (frow) {
      let da = frow.status
      let s1 = new Date().getTime() //当前时间
      let s2 = new Date(frow.useEndTime).getTime() //结束时间
      let s3 = new Date(frow.useStartTime).getTime() // 开始时间
      if (da == 2) {
        return '已失效'
      }
      if (s2 - s1 < 0) {
        return '已结束'
      }
      if (s3 < s1 && s1 < s2) {
        return '进行中'
      }
      if (s1 < s3) {
        return '未开始'
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.top-content {
  background: #f2f2f2;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 10px;
  .pad {
    padding: 10px 0;
  }
  .top-content-tit {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .item {
      margin-left: 5px;
    }
  }
}
</style>
